const SEARCH_API_VERSION = "0.2.0";
const _NTUBE_WEBP_ALLOWED = window.Config && window.Config.appearance.enable_webp;
if (!String.prototype.replaceAll) {
	String.prototype.replaceAll = function (searchStr, replaceStr) {
		var str = this;
		if (str.indexOf(searchStr) === -1) {
			return str;
		}
		return str.replace(searchStr, replaceStr).replaceAll(searchStr, replaceStr);
	};
}
const SearchBar = {
	apiVersion: SEARCH_API_VERSION,
	init: function () {
		/*try {
            if (isMobile || is_iPhoneOS()) {
                id("search_bar").style.width = "23vw";
            }
        }catch (e) {
            console.error(e);
        }*/
		try {
			document.querySelector("#search_overlay > div:nth-child(2) > div:nth-child(2) > button").style.fontFamily = "inherit";
		} catch (e) {}
		try {
			id("search_bar").addEventListener("keypress", function (event) {
				var keyCode = event.which || event.keyCode;
				if (keyCode == 13) {
					event.preventDefault();
					SearchBar.search();
				}
			});
		} catch (e) {
			console.error(e);
		}
		try {
			window.search_start = function (e) {
				SearchBar.search(e);
			};
		} catch (e) {
			console.error(e);
		}
	},
	search: function (continuation) {
		var strictSearch = false;
		if (window.__SETTINGS_OBJECT && window.__SETTINGS_OBJECT.global && window.__SETTINGS_OBJECT.global.experiments && window.__SETTINGS_OBJECT.global.strict_search_intitle) {
			strictSearch = window.__SETTINGS_OBJECT.global.strict_search_intitle;
		}
		try {
			const query = id("search_bar").value;
			if (query.startsWith(":")) {
				// TODO: Redirect to nTube Commander
				return;
			} else if (query == null || query.length == 0 || query === " " || query === "") {
				return;
			} else if (isValidYTURL(query)) {
				var info = getVideoInfoFromURL(query);
				if (info === null || info === undefined || !info["type"] || info["type"] === "invalid") {
					return;
				} else {
					var time = info["time"];
					var playlist = info["playlist_id"];
					if (info["type"] === "standard" || info["type"] === "standard-consent") {
						var videoID = info["id"];
						var newURL = "/watch?v=" + videoID + "&redirect=from_search_query";
						if (time !== null && time !== undefined) {
							newURL += "&t=" + time;
						}
						if (playlist !== null && playlist !== undefined) {
							newURL += "&list=" + playlist;
						}
						document.location.href = newURL;
					} else if (info["type"] === "embed") {
						var newURL = "/watch?v=" + info["id"] + "&redirect=from_search_query";
						document.location.href = newURL;
					} else {
						var videoID = info["id"];
						var newURL = "/watch?v=" + videoID + "&redirect=from_search_query";
						if (time !== null && time !== undefined) {
							newURL += "&t=" + time;
						}
						if (playlist !== null && playlist !== undefined) {
							newURL += "&list=" + playlist;
						}
						document.location.href = newURL;
					}
				}
			} else {
				run_promise(function () {
					if (window.loadVideo && (continuation === null || continuation === undefined || continuation.length === 0)) {
						try {
							id("search_overlay").style.opacity = "0";
							id("search_overlay").classList.remove("search_hidden");
							fadein(id("search_overlay"));
						} catch (ex) {
							console.error(ex);
						}
					} else {
						try {
							id("search_overlay").classList.remove("search_hidden");
						} catch (ex) {
							console.error(ex);
						}
					}
				});
				var trueQuery = query;
				if (strictSearch && !query.contains("intitle:")) {
					trueQuery = "intitle:" + query;
				}
				var rurl = "/search_video_api?query=" + encodeURIComponent(trueQuery) + "&version=1.1&apiVer=" + SEARCH_API_VERSION;
				if (continuation !== undefined && continuation !== null && continuation.length > 0) {
					rurl += "&cont=" + continuation;
				}
				id("search_query_display_string").innerHTML = decodeURIComponent(trueQuery).replace("+", " ");
				request(
					rurl,
					null,
					function (exception) {
						console.error(exception);
						alert("Failed to search for '" + query + "'.\nCheck your browser console.");
						run_promise(function () {
							id("search_overlay").style.cursor = "";
							id("_search_load_more").disabled = false;
							id("_search_load_more").style.filter = "";
						});
					},
					function (data) {
						const jsonObject = JSON.parse(data);
						run_promise(function () {
							id("search_overlay").style.cursor = "";
							id("_search_load_more").disabled = false;
							id("_search_load_more").style.filter = "";
						});
						if (jsonObject.error) {
							if (jsonObject["error"]["reason"] && jsonObject["error"]["reason"] === "NCAPTCHA_SOLUTION_REQUIRED") {
								alert("Failed to search for item.\nYour nCaptcha session has expired, you'll need to refresh this page to solve a new challenge.");
							} else {
								alert("Failed to search for item.\nCheck your browser console.");
							}
							console.error("SEARCH_ERROR_PRESENT", jsonObject.error);
							return;
						} else {
							window.jsonSearchObject = jsonObject;
							if (continuation === null || continuation === undefined) {
								id("_search_results").innerHTML = "";
							}
							id("_search_load_more").onclick = function () {
								if (jsonObject && jsonObject.query && jsonObject.query !== null && jsonObject.query !== undefined) {
									id("search_bar").value = decodeURIComponent(jsonObject.query).replaceAll("+", " ");
								}
								SearchBar.search(jsonObject.continuation);
							};
							var videos = jsonObject.videos;
							for (var i = 0; i < videos.length; i++) {
								var video = videos[i];
								if (video.type === "video") {
									var api_input = {
										type: "video",
										data: {
											thumbnail: video.thumbnail,
											title: video.title,
											duration: video.lengthText,
											link: video.url,
											channel: video.author,
											animated_thumbnail: video.hoverURL,
											viewCount: video.viewCount,
										},
									};
									SearchBar.___submit_search_result(api_input);
								} else if (video.type === "channel") {
									var api_input = {
										type: "channel",
										data: {
											thumbnail: video.thumbnail,
											title: video.title,
											link: video.url,
										},
									};
									SearchBar.___submit_search_result(api_input);
								} else if (video.type === "playlist") {
									var api_input = {
										type: "playlist",
										data: {
											thumbnail: video.thumbnail,
											title: video.title,
											text: video.text,
											link: video.url,
										},
									};
									SearchBar.___submit_search_result(api_input);
								} else if (video.type === "show") {
									var api_input = {
										type: "show",
										data: {
											thumbnail: video.thumbnail,
											title: video.title,
											text: video.text,
											link: video.url,
											channel: video.author,
										},
									};
									SearchBar.___submit_search_result(api_input);
								} else {
									console.warn("[search.js] Unknown type: " + video.type);
								}
							}
						}
					}
				);
				run_promise(function () {
					id("search_overlay").style.cursor = "wait";
					id("_search_load_more").disabled = true;
					id("_search_load_more").style.filter = "grayscale(1)";
				});
			}
		} catch (e) {
			console.error(e);
		}
	},
	___submit_search_result: function (object) {
		/**
          * object model: {
              type: "" // channel/video/playlist
              data: {}
          }
          */
		var __no_add = false;
		const div = document.createElement("div");
		div.classList.add("search_video", "poly-item", "search_video_poly");
		div.style.marginBottom = "5px";
		/*<div class="poly-item related-div-core">
               <a href="" style="color: inherit; text-decoration: none;">
               <img class="related-div-img" src="https://i.ytimg.com/v/fi9dfsd/mqdefault.jpg">
               <div style="display: inline-block; padding-left: 5px; padding-right: 5px;">
                   <p style="font-weight: bold; font-size: large; vertical-align: top;">$NEW_RELATED_TITLE</p>
                   <p style="font-size: small; vertical-align: bottom;">$CHANNEL_NAME &centerdot; $DURATION</p>
               </div>
           </a>
       </div>*/
		if (object.type === "channel") {
			const link0 = document.createElement("a");
			link0.href = object.data.link;
			const image0 = document.createElement("img");
			image0.style.verticalAlign = "middle";
			image0.style.display = "table-row";
			image0.style.width = "auto";
			image0.style.height = "90px";
			image0.loading = "lazy";
			image0.decoding = "async";
			image0.referrerPolicy = "no-referrer";
			image0.onload = function () {
				if (this.naturalWidth === 120) {
					image0.src = object.data.thumbnail.replaceAll("sqdefault.jpg", "mqdefault.jpg");
				}
			};
			if (object && object.data && isValidObject(object.data.animated_thumbnail) && _NTUBE_WEBP_ALLOWED) {
				const im = object.data.thumbnail;
				const ia = object.data.animated_thumbnail;
				image0.src = im;
				image0.onmouseover = function () {
					image0.src = ia;
				};
				image0.onmouseout = function () {
					image0.src = im;
				};
			} else {
				image0.src = object.data.thumbnail;
			}
			link0.appendChild(image0);
			div.appendChild(link0);
			var contentDiv = document.createElement("div");
			contentDiv.classList.add("search_video_idiv");
			contentDiv.style.verticalAlign = "middle";
			contentDiv.style.paddingLeft = "5px";
			contentDiv.style.paddingRight = "5px";
			var videoTitle = document.createElement("h3");
			videoTitle.style.verticalAlign = "middle";
			videoTitle.style.margin = "0px auto";
			videoTitle.innerHTML = object.data.title;
			contentDiv.appendChild(videoTitle);
			var videoDescription = document.createElement("p");
			videoDescription.style.verticalAlign = "bottom";
			videoDescription.style.margin = "0px";
			videoDescription.style.fontSize = "small";
			videoDescription.innerHTML = "CHANNEL";
			contentDiv.appendChild(videoDescription);
			div.appendChild(contentDiv);
		} else if (object.type === "video" || object.type === "show") {
			const link1 = document.createElement("a");
			if (window.loadVideo) {
				link1.onclick = function () {
					if (window.fadeout && window.hide) {
						fadeout(id("search_overlay"), function () {
							id("search_overlay").classList.add("search_hidden");
							id("search_overlay").style.opacity = "1";
						});
					}
					loadVideo(object.data.link);
					if (window.history && window.history.pushState) {
						try {
							history.pushState({}, null, object.data.link.replace("/watch?", "/watch_next?"));
						} catch (E) {
							console.error("Failed to push history.", E);
						}
					}
				};
			} else {
				link1.href = object.data.link;
			}
			const image1 = document.createElement("img");
			image1.style.verticalAlign = "middle";
			image1.style.display = "table-row";
			image1.style.width = "160px";
			image1.style.height = "90px";
			image1.loading = "lazy";
			image1.decoding = "async";
			image1.referrerPolicy = "no-referrer";
			image1.onload = function () {
				if (this.naturalWidth === 120) {
					image1.src = object.data.thumbnail.replaceAll("sqdefault.jpg", "mqdefault.jpg");
				}
			};
			if (object && object.data && isValidObject(object.data.animated_thumbnail) && _NTUBE_WEBP_ALLOWED) {
				const im1 = object.data.thumbnail;
				const ia1 = object.data.animated_thumbnail;
				image1.src = im1;
				image1.onmouseover = function () {
					image1.src = ia1;
				};
				image1.onmouseout = function () {
					image1.src = im1;
				};
			} else {
				image1.src = object.data.thumbnail;
			}
			link1.appendChild(image1);
			div.appendChild(link1);
			var contentDiv = document.createElement("div");
			contentDiv.classList.add("search_video_idiv");
			contentDiv.style.verticalAlign = "middle";
			contentDiv.style.paddingLeft = "5px";
			contentDiv.style.paddingRight = "5px";
			var videoTitle = document.createElement("h3");
			videoTitle.style.verticalAlign = "middle";
			videoTitle.style.margin = "0px auto";
			videoTitle.innerHTML = object.data.title;
			contentDiv.appendChild(videoTitle);
			var videoDescription = document.createElement("p");
			videoDescription.style.verticalAlign = "bottom";
			videoDescription.style.margin = "0px";
			videoDescription.style.fontSize = "small";
			if (object.type === "show") {
				videoDescription.innerHTML = object.data.text;
			} else {
				videoDescription.innerHTML = object.data.duration + " &centerdot; " + object.data.viewCount + " &centerdot; " + object.data.channel;
			}
			contentDiv.appendChild(videoDescription);
			div.appendChild(contentDiv);
			/*const img2 = document.createElement("img");
			img2.src = object.data.thumbnail;
			img2.loading = "lazy";
			img2.decoding = "async";
			var vlink = document.createElement("a");
			vlink.classList.add("search-link");
			if (window.loadVideo) {
				vlink.onclick = function () {
					if (window.fadeout && window.hide) {
						fadeout(id("search_overlay"), function () {
							id("search_overlay").classList.add("search_hidden");
							id("search_overlay").style.opacity = "1";
						});
					}
					loadVideo(object.data.link);
					if (window.history && window.history.pushState) {
						try {
							history.pushState({}, null, object.data.link.replace("/watch?", "/watch_next?"));
						} catch (E) {
							console.error("Failed to push history.", E);
						}
					}
				};
			} else {
				vlink.href = object.data.link;
			}
			img2.onload = function () {
				if (this.naturalWidth === 120) {
					img2.src = object.data.thumbnail.replaceAll("sqdefault.jpg", "mqdefault.jpg");
				}
			};
			if (isValidObject(object.data.animated_thumbnail) && window.Config && window.Config.appearance.enable_webp) {
				img2.onmouseover = function () {
					img2.src = object.data.animated_thumbnail;
					img2.style.height = "120px";
				};
				img2.onmouseout = function () {
					img2.src = object.data.thumbnail;
					img2.style.height = "";
				};
			}
			img2.classList.add("search-img");
			vlink.appendChild(img2);
			var ib = document.createElement("div");
			vlink.appendChild(ib);
			ib.classList.add("search-inner-block");
			var title = document.createElement("p");
			title.style.fontWeight = "bold";
			title.style.fontSize = "large";
			title.style.verticalAlign = "top";
			title.innerHTML = object.data.title;
			ib.appendChild(title);
			var subtext = document.createElement("p");
			subtext.style.fontSize = "small";
			subtext.style.verticalAlign = "bottom";
			if (object.type === "show") {
				subtext.innerHTML = object.data.text;
			} else {
				subtext.innerHTML = object.data.duration + " &centerdot; " + object.data.viewCount + " &centerdot; " + object.data.channel;
			}
			ib.appendChild(subtext);
			div.appendChild(vlink);*/
		} else if (object.type === "playlist") {
			const link2 = document.createElement("a");
			link2.href = object.data.link;
			const image2 = document.createElement("img");
			image2.style.verticalAlign = "middle";
			image2.style.display = "table-row";
			image2.style.width = "auto";
			image2.style.height = "90px";
			image2.loading = "lazy";
			image2.decoding = "async";
			image2.referrerPolicy = "no-referrer";
			image2.onload = function () {
				if (this.naturalWidth === 120) {
					image2.src = object.data.thumbnail.replaceAll("sqdefault.jpg", "mqdefault.jpg");
				}
			};
			if (object && object.data && isValidObject(object.data.animated_thumbnail) && _NTUBE_WEBP_ALLOWED) {
				const im2 = object.data.thumbnail;
				const ia2 = object.data.animated_thumbnail;
				image2.src = im2;
				image2.onmouseover = function () {
					image2.src = ia2;
				};
				image2.onmouseout = function () {
					image2.src = im2;
				};
			} else {
				image2.src = object.data.thumbnail;
			}
			link2.appendChild(image2);
			div.appendChild(link2);
			var contentDiv = document.createElement("div");
			contentDiv.classList.add("search_video_idiv");
			contentDiv.style.verticalAlign = "middle";
			contentDiv.style.paddingLeft = "5px";
			contentDiv.style.paddingRight = "5px";
			var videoTitle = document.createElement("h3");
			videoTitle.style.verticalAlign = "middle";
			videoTitle.style.margin = "0px auto";
			videoTitle.innerHTML = object.data.title;
			contentDiv.appendChild(videoTitle);
			var videoDescription = document.createElement("p");
			videoDescription.style.verticalAlign = "bottom";
			videoDescription.style.margin = "0px";
			videoDescription.style.fontSize = "small";
			videoDescription.innerHTML = object.data.text;
			contentDiv.appendChild(videoDescription);
			div.appendChild(contentDiv);
			/*var img = document.createElement("img");
			var vlink = document.createElement("a");
			vlink.classList.add("search-link");
			vlink.href = object.data.link;
			img.src = object.data.thumbnail;
			img.loading = "lazy";
			img.decoding = "async";
			img.onload = function () {
				if (this.naturalWidth === 120) {
					img.src = object.data.thumbnail.replaceAll("sqdefault.jpg", "mqdefault.jpg");
				}
			};
			if (isValidObject(object.data.animated_thumbnail) && window.Config && window.Config.appearance.enable_webp) {
				img.onmouseover = function () {
					img.src = object.data.animated_thumbnail;
					img.style.height = "120px";
				};
				img.onmouseout = function () {
					img.src = object.data.thumbnail;
					img.style.height = "";
				};
			}
			img.classList.add("search-img");
			vlink.appendChild(img);
			var ib = document.createElement("div");
			ib.classList.add("search-inner-block");
			vlink.appendChild(ib);
			var title = document.createElement("p");
			title.style.fontWeight = "bold";
			title.style.fontSize = "large";
			title.style.verticalAlign = "top";
			title.innerHTML = object.data.title;
			ib.appendChild(title);
			var subtext = document.createElement("p");
			subtext.style.fontSize = "small";
			subtext.style.verticalAlign = "bottom";
			subtext.innerHTML = object.data.text;
			ib.appendChild(subtext);
			div.appendChild(vlink);*/
		} else {
			console.error("Unsupported type: " + object.type);
			__no_add = true;
			return;
		}
		if (!__no_add) {
			id("_search_results").appendChild(div);
		}
	},
};
window.SearchBar = SearchBar;
